<template>
  <div class="operate_log_container">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleTabClick">
      <!-- 操作日志 -->
      <el-tab-pane label="操作日志" name="operation-log">
        <div class="operate_log">
          <div class="header">
            <date-range @change="handleOperateLogDateChange" />
            <el-select
              v-model="operateLogFilterValue.empType"
              placeholder="请选择人员类型"
              filterable
              clearable
              @change="getSysLog"
              @clear="getSysLog"
            >
              <el-option
                v-for="(item, index) in empTypeOptional"
                :key="item"
                :value="index + 1"
                :label="item"
              />
            </el-select>
            <el-select
              v-model="operateLogFilterValue.type"
              placeholder="请选择操作类型"
              filterable
              clearable
              @change="getSysLog"
              @clear="getSysLog"
            >
              <el-option
                v-for="(item, index) in typeOptional"
                :key="item"
                :value="index + 1"
                :label="item"
              />
            </el-select>
            <el-input
              v-model.trim="operateLogFilterValue.keyword"
              placeholder="请输入操作账号/操作人员名称"
              class="input"
              clearable
              @keyup.enter="getSysLog"
              @clear="getSysLog"
            />
            <HButton type="primary" @click="getSysLog">
              <el-icon> <Search /> </el-icon>搜索
            </HButton>
            <HButton @click="onSysLogReset">
              <el-icon> <RefreshRight /> </el-icon>重置
            </HButton>
          </div>
          <div class="table">
            <el-table v-loading="getSystemLogLoading" border :data="systemLogList" height="100%">
              <template #empty>
                <el-empty description="暂无数据" />
              </template>
              <!--序号-->
              <el-table-column
                show-overflow-tooltip
                type="index"
                label="序号"
                width="50"
                fixed="left"
                :align="'center'"
              />

              <!--手机号-->
              <el-table-column show-overflow-tooltip prop="account" label="手机号" width="106" />

              <!--账户名-->
              <el-table-column show-overflow-tooltip prop="name" label="账户名" width="130" />

              <!--人员类型-->
              <el-table-column show-overflow-tooltip prop="empType" label="人员类型" width="110">
                <template #default="scope">
                  <template v-if="scope.row.empType === 1">PC端</template>
                  <template v-else-if="scope.row.empType === 2">公司报单移动端</template>
                  <template v-else-if="scope.row.empType === 3">网点移动端</template>
                  <template v-else>出库移动端</template>
                </template>
              </el-table-column>

              <!--浏览器-->
              <el-table-column
                show-overflow-tooltip
                prop="browserDevice"
                label="浏览器"
                min-width="90"
              />

              <!--IP地址-->
              <el-table-column show-overflow-tooltip prop="ip" label="IP地址" width="98" />

              <!--请求地址-->
              <el-table-column show-overflow-tooltip prop="path" label="请求地址" min-width="200" />

              <!--功能-->
              <el-table-column show-overflow-tooltip prop="remark" label="功能" min-width="200" />

              <!--操作类型-->
              <el-table-column show-overflow-tooltip prop="type" label="操作类型" width="74">
                <template #default="scope">
                  <span v-if="scope.row.type === 1">新增</span>
                  <span v-else-if="scope.row.type === 2">删除</span>
                  <span v-else>修改</span>
                </template>
              </el-table-column>

              <!--操作时间-->
              <el-table-column
                show-overflow-tooltip
                prop="createTime"
                label="操作时间"
                width="128"
              />

              <!--结果-->
              <el-table-column
                prop="success"
                label="结果"
                width="72"
                :align="'center'"
                fixed="right"
              >
                <template #default="scope">
                  <div class="flex_justify_center">
                    <HStatus v-if="scope.row.success">成功</HStatus>
                    <HStatus v-else type="error">失败</HStatus>
                  </div>
                </template>
              </el-table-column>

              <!--操作-->
              <el-table-column fixed="right" width="50" label="操作">
                <template #default="scope">
                  <HLink v-if="scope.row.success" disabled>查看</HLink>
                  <HLink v-else @click="handleOperateContentClick(scope.row)">查看</HLink>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="pagination">
            <Pagination
              ref="operateLogPaginationRef"
              :list_total="systemLogPagination.total"
              @size-change="getSysLog"
              @current-change="getSysLog(false)"
            />
          </div>
        </div>
        <!-- 操作内容弹窗 -->
        <h-drawer
          v-model="operateLogDialogVisible"
          title="操作内容"
          :width="700"
          unit="px"
          :loading="getOperateLogContentLoading"
        >
          <div class="operate-content">
            <template v-if="logOperateContent.param === '' && logOperateContent.content === ''">
              <el-empty description="暂无数据" />
            </template>
            <template v-else>
              <div class="param">
                <div class="title">请求参数：</div>
                <template v-if="logOperateContent.param === ''"> 暂无请求参数 </template>
                <template v-else>
                  <div class="param-content">{{ logOperateContent.param }}</div>
                </template>
              </div>

              <div class="title">报错信息(仅供技术支持排查问题使用)：</div>
              <template v-if="logOperateContent.content === ''"> 暂无报错信息 </template>
              <template v-else>
                <div class="info-content">{{ logOperateContent.content }}</div>
              </template>
            </template>
          </div>
        </h-drawer>
      </el-tab-pane>

      <!-- 消息日志 -->
      <el-tab-pane label="消息日志" name="message-log">
        <div class="message_log">
          <div class="header">
            <HPlainButton @click="onShowSysUpgrade">导出</HPlainButton>
            <div class="search">
              <date-range />
              <el-select v-model="value5" placeholder="请选择" filterable clearable>
                <el-option v-for="item in options" :key="item.value" :value="item.value" />
              </el-select>
              <el-select v-model="value6" placeholder="请选择" filterable clearable>
                <el-option v-for="item in options" :key="item.value" :value="item.value" />
              </el-select>
              <el-select v-model="select" placeholder="选择">
                <el-option label="工单编号" value="1" />
                <el-option label="工单编号" value="2" />
                <el-option label="工单编号" value="3" />
              </el-select>
              <el-input v-model.trim="input" placeholder="检索" class="input-with-select" />
              <h-button type="primary" @click="onShowSysUpgrade">
                <el-icon>
                  <Search></Search>
                </el-icon>
                搜索
              </h-button>
            </div>
          </div>
          <div class="table">
            <el-table border stripe resizable :data="tableData" height="100%">
              <el-table-column
                show-overflow-tooltip
                type="index"
                :index="indexMethod1"
                label="序号"
                width="50"
                fixed="left"
                :align="'center'"
              />
              <el-table-column show-overflow-tooltip prop="name" label="消息时间" width="200" />
              <el-table-column show-overflow-tooltip prop="date" label="接收公司" width="250" />
              <el-table-column show-overflow-tooltip prop="state" label="消息类型" width="200" />
              <el-table-column show-overflow-tooltip prop="city" label="消息信息" min-width="200" />
            </el-table>
          </div>
          <div class="pagination">
            <Pagination ref="messageLogPagination" :list-total="12" />
          </div>
        </div>
      </el-tab-pane>

      <!-- 登录日志 -->
      <el-tab-pane label="登录日志" name="login-log">
        <div class="login_log">
          <div class="header">
            <el-input
              v-model.trim="loginLogFilterValue.name"
              placeholder="登录账号/登录公司名"
              @keyup.enter="getLoginLog"
              @clear="getLoginLog"
            />
            <HButton type="primary" @click="getLoginLog">
              <el-icon>
                <Search />
              </el-icon>
              搜索
            </HButton>
            <HButton @click="onLoginLogReset">
              <el-icon>
                <RefreshRight />
              </el-icon>
              重置
            </HButton>
          </div>
          <div class="table">
            <el-table v-loading="getLoginLogLoading" border :data="loginLogList" height="100%">
              <el-table-column
                show-overflow-tooltip
                type="index"
                label="序号"
                width="50"
                fixed="left"
                :align="'center'"
              />
              <el-table-column
                show-overflow-tooltip
                prop="createTime"
                label="登录时间"
                width="140"
              />
              <el-table-column show-overflow-tooltip prop="account" label="登录账号" width="120" />
              <el-table-column show-overflow-tooltip prop="name" label="账号名" width="140" />
              <el-table-column show-overflow-tooltip prop="mode" label="登录类型" width="140" />
              <el-table-column
                show-overflow-tooltip
                prop="browserDevice"
                label="登录产品"
                width="130"
              />
              <el-table-column show-overflow-tooltip prop="ip" label="登录IP" width="100" />
              <el-table-column
                prop="success"
                label="登录状态"
                width="80"
                fixed="right"
                :align="'center'"
              >
                <template #default="scope">
                  <div class="flex_justify_center">
                    <HStatus v-if="scope.row.success">成功</HStatus>
                    <HStatus v-else type="error">失败</HStatus>
                  </div>
                </template>
              </el-table-column>
              <el-table-column show-overflow-tooltip prop="device" label="产品数量" width="80" />
              <el-table-column
                show-overflow-tooltip
                prop="message"
                label="登录消息"
                min-width="200"
              />
            </el-table>
          </div>
          <div class="pagination">
            <Pagination
              ref="loginLogPaginationRef"
              :list_total="loginLogPagination.total"
              @size-change="getLoginLog"
              @current-change="getLoginLog(false)"
            />
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="SAP调用日志" name="sap-call-log-list">
        <sap-call-log-list ref="sapCallLogListInstance" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { onMounted, ref, nextTick } from 'vue'
  import { Search, RefreshRight } from '@element-plus/icons-vue'
  import { ElMessage, TabsPaneContext } from 'element-plus'
  import busicJournalService from './service'
  import { GetLogListParam, GetSysListParam } from './types'
  import DateRange from '@/components/DateRange.vue'
  import routeComponentName from '@/config/route-component-name'
  import SapCallLogList from './components/sap-call-log-list.vue'

  defineOptions({
    name: routeComponentName.setting.operateLog,
  })

  const {
    loginLogList,
    systemLogList,
    logOperateContent,
    loginLogPagination,
    systemLogPagination,
    getLoginLogLoading,
    getSystemLogLoading,
    getOperateLogContentLoading,
    getLoginLogList,
    getSystemLogList,
    getLogOperateContent,
  } = busicJournalService

  const sapCallLogListInstance = ref<InstanceType<typeof SapCallLogList> | null>(null)

  // 操作日志筛选 - 用于绑定到组件里
  const operateLogFilterValue = ref<{
    empType: '' | 1 | 2 | 3 | 4
    type: '' | 1 | 2 | 3
    keyword: string
    startDate: string
    endDate: string
  }>({
    empType: '',
    type: '',
    keyword: '',
    startDate: '',
    endDate: '',
  })

  const handleOperateLogDateChange = (param: {
    startDate: string
    endDate: string
    isStartDateGreaterThanEndDate: boolean
  }) => {
    if (param.isStartDateGreaterThanEndDate) {
      ElMessage({
        type: 'error',
        message: '开始日期不能大于结束日期',
        duration: 5000,
        showClose: true,
        plain: true,
      })
      return false
    }
    operateLogFilterValue.value.startDate = param.startDate
    operateLogFilterValue.value.endDate = param.endDate
    getSysLog()
  }

  const onShowSysUpgrade = () => {
    ElMessage({
      type: 'success',
      message: '正在升级维护中，敬请期待...',
      duration: 5000,
      showClose: true,
      plain: true,
    })
  }

  // 登录日志筛选 - 用于绑定到组件里
  const loginLogFilterValue = ref({
    name: '',
  })

  // 操作类型的可选项
  const empTypeOptional = ['PC端', '公司报单移动端', '网点移动端', '出入库移动端']

  // 操作类型的可选项
  const typeOptional = ['新增', '删除', '修改']

  // 日期范围
  const dateRange = ref('')

  // 系统操作日志列表分页组件实例
  const operateLogPaginationRef = ref<InstanceType<typeof Pagination> | null>(null)

  // 登录日志列表分页组件实例
  const loginLogPaginationRef = ref<InstanceType<typeof Pagination> | null>(null)

  // 操作日志筛选条件 - 用于传递到请求里当做请求参数
  const operateFilterCondition = ref<GetSysListParam>({
    empType: null,
    keyword: '',
    limit: 0,
    operateEndTime: '',
    operateStartTime: '',
    page: 0,
    type: null,
  })

  // 登录筛选条件 - 用于传递到请求里当做请求参数
  const loginFilterCondition = ref<GetLogListParam>({
    name: '',
    limit: 0,
    page: 0,
  })

  // 选中的标签
  const activeName = ref('operation-log')

  // 操作内容弹窗状态
  const operateLogDialogVisible = ref(false)

  // 获取系统操作日志列表
  const getSysLog = (val = true) => {
    if (val) operateLogPaginationRef.value.setPage()
    const { empType, type, startDate, endDate, keyword } = operateLogFilterValue.value
    const { size, current } = operateLogPaginationRef.value

    if (empType === '') {
      operateFilterCondition.value.empType = null
    } else {
      operateFilterCondition.value.empType = Number(
        empType,
      ) as typeof operateFilterCondition.value.empType
    }

    if (type === '') {
      operateFilterCondition.value.type = null
    } else {
      operateFilterCondition.value.type = Number(type) as typeof operateFilterCondition.value.type
    }

    operateFilterCondition.value.operateStartTime = startDate ? startDate : ''
    operateFilterCondition.value.operateEndTime = endDate ? endDate : ''
    operateFilterCondition.value.keyword = keyword.trim()
    operateFilterCondition.value.limit = size
    operateFilterCondition.value.page = current
    getSystemLogList(operateFilterCondition.value)
  }

  // 获取登录日志列表
  const getLoginLog = (val = true) => {
    if (val) loginLogPaginationRef.value.setPage()
    loginFilterCondition.value.name = loginLogFilterValue.value.name.trim()
    loginFilterCondition.value.limit = loginLogPaginationRef.value.size
    loginFilterCondition.value.page = loginLogPaginationRef.value.current
    getLoginLogList(loginFilterCondition.value)
  }

  // 重置操作日志筛选条件事件
  const onSysLogReset = () => {
    operateLogFilterValue.value.empType = ''
    operateLogFilterValue.value.type = ''
    operateLogFilterValue.value.startDate = ''
    operateLogFilterValue.value.endDate = ''
    operateLogFilterValue.value.keyword = ''
    operateFilterCondition.value.empType = null
    operateFilterCondition.value.type = null
    operateFilterCondition.value.operateStartTime = ''
    operateFilterCondition.value.operateEndTime = ''
    operateFilterCondition.value.keyword = ''
    operateFilterCondition.value.limit = operateLogPaginationRef.value.size
    operateFilterCondition.value.page = operateLogPaginationRef.value.current
    getSysLog()
  }

  // 重置登录日志筛选条件事件
  const onLoginLogReset = () => {
    loginLogFilterValue.value.name = ''
    loginFilterCondition.value.name = ''
    loginFilterCondition.value.limit = loginLogPaginationRef.value.size
    loginFilterCondition.value.page = loginLogPaginationRef.value.current
    getLoginLog()
  }

  // 操作内容点击事件
  const handleOperateContentClick = (param) => {
    operateLogDialogVisible.value = true
    getLogOperateContent(param.id).then(() => {
      logOperateContent.value.param = ''
      const { param } = logOperateContent.value
      if (param !== '') {
        logOperateContent.value.param = JSON.stringify(JSON.parse(param), null, '\t')
      }
    })
  }

  // 标签页点击事件
  const handleTabClick = (tab: TabsPaneContext) => {
    nextTick(() => {
      switch (tab.props.name) {
        case 'operation-log':
          getSysLog()
          break
        case 'login-log':
          getLoginLog()
          break
        case 'sap-call-log-list':
          if (sapCallLogListInstance.value) {
            sapCallLogListInstance.value.getList()
          }
          break
      }
    })
  }

  //列表序号
  const indexMethod1 = (index: number) => {
    return (index + 1) * 1
  }
  const value5 = ref('')
  const value6 = ref('')

  const size = ref<'default' | 'large' | 'small'>('large')
  const input = ref('')
  const select = ref('')
  const options = [
    {
      value: '全部类型',
    },
    {
      value: '全部品牌',
    },
    {
      value: '全部分类',
    },
  ]
  const shortcuts = [
    {
      text: '上周',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
        return [start, end]
      },
    },
    {
      text: '上个月',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
        return [start, end]
      },
    },
    {
      text: '上 3 个月',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
        return [start, end]
      },
    },
  ]

  const tableData = [
    {
      date: '公司备88888888888',
      name: '空调外机风叶（122.54411）',
      state: 'California',
      city: '深圳市南山区维修店',
      address: '2023-04-26 11:31:01',
      zip: 'CA 90036',
      tag: 'Home',
    },
    {
      date: '20230602590500824',
      name: '2016-05-02',
      state: 'California',
      city: '自动派单测试',
      address: 'No. 189, Grove St, Los Angeles',
      zip: 'CA 90036',
      tag: 'Home',
    },
    {
      date: '2016-05-02',
      name: 'Tom',
      state: 'California',
      city: 'Los Angeles',
      address: 'No. 189, Grove St, Los Angeles',
      zip: 'CA 90036',
      tag: 'Office',
    },
    {
      date: '2016-05-04',
      name: 'Tom',
      state: 'California',
      city: 'Los Angeles',
      address: 'No. 189, Grove St, Los Angeles',
      zip: 'CA 90036',
      tag: 'Home',
    },
    {
      date: '2016-05-01',
      name: 'Tom',
      state: 'California',
      city: 'Los Angeles',
      address: 'No. 189, Grove St, Los Angeles',
      zip: 'CA 90036',
      tag: 'Office',
    },
    {
      date: '2016-05-03',
      name: 'Tom',
      state: 'California',
      city: 'Los Angeles',
      address: 'No. 189, Grove St, Los Angeles',
      zip: 'CA 90036',
      tag: 'Home',
    },
    {
      date: '2016-05-02',
      name: 'Tom',
      state: 'California',
      city: 'Los Angeles',
      address: 'No. 189, Grove St, Los Angeles',
      zip: 'CA 90036',
      tag: 'Office',
    },
    {
      date: '2016-05-04',
      name: 'Tom',
      state: 'California',
      city: 'Los Angeles',
      address: 'No. 189, Grove St, Los Angeles',
      zip: 'CA 90036',
      tag: 'Home',
    },
    {
      date: '2016-05-01',
      name: 'Tom',
      state: 'California',
      city: 'Los Angeles',
      address: 'No. 189, Grove St, Los Angeles',
      zip: 'CA 90036',
      tag: 'Office',
    },
    {
      date: '2016-05-03',
      name: 'Tom',
      state: 'California',
      city: 'Los Angeles',
      address: 'No. 189, Grove St, Los Angeles',
      zip: 'CA 90036',
      tag: 'Home',
    },
    {
      date: '2016-05-02',
      name: 'Tom',
      state: 'California',
      city: 'Los Angeles',
      address: 'No. 189, Grove St, Los Angeles',
      zip: 'CA 90036',
      tag: 'Office',
    },
    {
      date: '2016-05-04',
      name: 'Tom',
      state: 'California',
      city: 'Los Angeles',
      address: 'No. 189, Grove St, Los Angeles',
      zip: 'CA 90036',
      tag: 'Home',
    },
  ]

  onMounted(() => {
    switch (activeName.value) {
      case 'operation-log':
        getSysLog()
        break
      case 'login-log':
        getLoginLog()
        break
    }
  })
</script>

<style scoped lang="scss">
  @import './index';
</style>
